//
//  WIFIDeviceSettingView.m
//  Router
//
//  Created by teki on 15/11/4.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "WIFIDeviceSetting.h"
#import "TKSlider.h"
#import "StationModel.h"
#import "WIFIHelper.h"
#import "UWDatePickerView.h"
#import "RenameView.h"
#import "BaseViewController.h"
#import "ResultTipView.h"
#import "UIAlertView+Block.h"
@interface WIFIDeviceSetting ()<UWDatePickerViewDelegate>


@property (nonatomic, strong) UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *offLineView;
@property (nonatomic, strong) ResultTipView *networkTipView;

@property (nonatomic, strong) UIView *contentView;

@property (weak, nonatomic) IBOutlet UILabel *deviceLabel;
@property (weak, nonatomic) IBOutlet UIButton *wifiSwitchButton;

@property (weak, nonatomic) IBOutlet TKSlider *mSlider;

@property (weak, nonatomic) IBOutlet UIButton *timeStartButton;
@property (weak, nonatomic) IBOutlet UIButton *timeStopButton;
@property (weak, nonatomic) IBOutlet UIButton *healthButton;

@property (nonatomic, strong) UWDatePickerView *pickerView;
@property (nonatomic, strong) RenameView *renameView;

@property (nonatomic, strong) WIFIHelper *wifiHelper;


@end


@implementation WIFIDeviceSetting

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initUI];
        [self setup];
    }
    return self;
}

- (void)awakeFromNib
{
    [self setup];
}

- (void)setup
{
    self.mSlider.minimumTrackTintColor = NavgationBarBackgroundColor;
    [self.mSlider setThumbImage:[UIImage imageNamed:@"home_adjust"] forState:UIControlStateNormal];
}


- (void)initUI
{
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:self.scrollView];
    [self.scrollView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    
    [self.scrollView addSubview:self.contentView];
    [self.contentView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    self.networkTipView = [[ResultTipView alloc] init];
    _networkTipView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.offLineView addSubview:self.networkTipView];
    
    
    [_networkTipView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.offLineView);
    }];
    _networkTipView.title =  @"信号低，WIFI未插上电?";
//    _networkTipView.buttonTitle = @"点击重试";
//    _networkTipView.buttonClicked = ^(){
//        NSLog(@"buttonPressed:");
//    };
    [_networkTipView resetViewContent];

}

#pragma mark -
#pragma mark   IBActions
- (void)showRenameView
{
    _renameView = [RenameView loadViewFromNib];
    _renameView.frame = [UIScreen mainScreen].bounds;
    _renameView.deviceName = _stationModel.alias;
    
    WEAKSELF
    [_renameView setAssureBlcok:^(NSString *name) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if ([name checkEmpty])
        {
            BaseViewController *controller = (BaseViewController *)[strongSelf parentViewController];
            [controller promptMessage:@"设备名不能为空!"];
            return ;
        }
        else{
            [strongSelf renameDeviceWithName:name];
        }

    }];
    [[self parentViewController].view addSubview:_renameView];
    
}



- (void)renameDeviceWithName:(NSString *)name
{
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    WEAKSELF
    [self.wifiHelper setDeviceAliasWithAlias:name deviceID:_stationModel.device_id masterDeviceID:wifi.device_id success:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString *set = responseObject[@"set"];
        if ( [set isEqualToString:@"success"])
        {
            strongSelf.deviceLabel.text = name;
        }
        else{
            
        }

    } failure:^(NSError *error) {
        
    }];
}


- (IBAction)editButtonPressed:(id)sender {
    [self showRenameView];
}

/// WIFI 开关
- (IBAction)WIFISwitchButtonPressed:(UIButton *)sender {
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    WEAKSELF
    [self.wifiHelper settingWIFIStatusWithDeviceID:_stationModel.device_id switchStatus:!self.wifiSwitchButton.selected power:ceil(self.mSlider.value)  masterDeviceID:wifi.device_id success:^(BOOL succ, id responseObject, NSString *msg) {
        if (responseObject) {
            NSString *set = responseObject[@"set"];
            if ([set isEqualToString:@"success"])
            {
                weakSelf.wifiSwitchButton.selected = !weakSelf.wifiSwitchButton.selected;
                weakSelf.stationModel.wifi_enable = weakSelf.wifiSwitchButton.selected;
            }
            else
            {
                
            }

        }
    } failure:^(NSError *error) {
        
    }];
}


- (IBAction)sliderValueChanged:(id)sender {
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    CGFloat orignalValue = _stationModel.link_quality;
    WEAKSELF
    [self.wifiHelper settingWIFIStatusWithDeviceID:_stationModel.device_id switchStatus:self.wifiSwitchButton.selected power:ceil(self.mSlider.value)  masterDeviceID:wifi.device_id success:^(BOOL succ, id responseObject, NSString *msg) {
        if (responseObject) {
            NSString *set = responseObject[@"set"];
            if ([set isEqualToString:@"success"])
            {
                
            }
            else
            {
                weakSelf.mSlider.value = orignalValue;
            }
            
        }
    } failure:^(NSError *error) {
        
    }];

}



- (IBAction)timeStartButtonPressed:(id)sender {
    [self setupDateView:DateTypeOfStart];
}

- (IBAction)timeStopButtonPressed:(id)sender {
    [self setupDateView:DateTypeOfEnd];

}

- (IBAction)healthButtonPressed:(id)sender {
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    NSString *startTime  = [self.timeStartButton titleForState:UIControlStateNormal];
    NSString *stopTime = [self.timeStopButton titleForState:UIControlStateNormal];
    WEAKSELF
    [self.wifiHelper settingWIFIHealthModelWithDeviceID:_stationModel.device_id wifi_on_time:startTime wifi_off_time:stopTime enable:!self.healthButton.selected masterDeviceID:wifi.device_id success:^(BOOL succ, id responseObject, NSString *msg) {
        if (responseObject) {
            NSString *set = responseObject[@"set"];
            if ([set isEqualToString:@"success"])
            {
                weakSelf.healthButton.selected = !weakSelf.healthButton.selected;
                weakSelf.stationModel.wifi_enable = weakSelf.healthButton.selected;
                
            }
        }

    } failure:^(NSError *error) {
        
    }];
}


- (void)setupDateView:(DateType)type {
    
    _pickerView = [UWDatePickerView instanceDatePickerView];
    _pickerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    _pickerView.delegate = self;
    _pickerView.type = type;
    [WINDOW addSubview:_pickerView];
    
}



- (void)getSelectDate:(NSString *)date type:(DateType)type {
    
    NSLog(@"时间:%@",date);
    switch (type) {
        case DateTypeOfStart:
            // TODO 日期确定选择
            [self.timeStartButton setTitle:date forState:UIControlStateNormal];
            break;
            
        case DateTypeOfEnd:
            // TODO 日期取消选择
            [self.timeStopButton setTitle:date forState:UIControlStateNormal];
            break;
        default:
            break;
    }
    
    [self requestSettingHealthTime];
}



- (void)requestSettingHealthTime
{
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    NSString *startTime  = [self.timeStartButton titleForState:UIControlStateNormal];
    NSString *stopTime = [self.timeStopButton titleForState:UIControlStateNormal];

    [self.wifiHelper settingWIFIHealthModelWithDeviceID:_stationModel.device_id wifi_on_time:startTime wifi_off_time:stopTime enable:!self.healthButton.selected masterDeviceID:wifi.device_id success:^(BOOL succ, id responseObject, NSString *msg) {
        if (responseObject){
            NSString *set = responseObject[@"set"];
            if ([set isEqualToString:@"success"])
            {
                
            }
        }
    } failure:^(NSError *error) {
        
    }];

}

#pragma mark -
#pragma mark   setter and getters
- (UIView *)contentView
{
    if (_contentView == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"WIFIDeviceSetting" owner:self options:nil];
        _contentView = [array firstObject];
    }
    return _contentView;
}



- (void)setStationModel:(StationModel *)stationModel
{
    _stationModel = stationModel;
    self.deviceLabel.text = stationModel.alias;
    self.wifiSwitchButton.selected = !stationModel.wifi_enable;
    [self.timeStartButton setTitle:stationModel.wifi_on_time forState:UIControlStateNormal];
    [self.timeStopButton setTitle:stationModel.wifi_off_time forState:UIControlStateNormal];
    self.healthButton.selected = !stationModel.wifi_time_enable;
    self.mSlider.value = stationModel.wifi_txpower;
    
    if ([stationModel.linkup isEqualToString:@"up"])
    {
        self.offLineView.hidden = YES;
    }
    else
    {
        self.offLineView.hidden = NO;
    }

    
}



- (WIFIHelper *)wifiHelper
{
    if (_wifiHelper == nil)
    {
        _wifiHelper = [[WIFIHelper alloc] init];
    }
    return _wifiHelper;
}


- (void)dealloc
{
    
}




- (IBAction)checkUpdateButtonPressed:(id)sender {
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    [self.wifiHelper checkUpdateWithDeviceID:self.stationModel.device_id masterDeviceID:wifi.device_id success:^(BOOL succ, id responseObject, NSString *msg) {
        if (responseObject) {
            NSInteger code = [responseObject[@"code"] integerValue];
            NSDictionary *version = responseObject[@"version"];
            BOOL hasNew = [version[@"has_new"] intValue] == 1;
            
            if (code == 0 && version && hasNew)
            {
                [self showNewVersionTip:wifi versionInfo:version];
            }else{
                [self showToastText:@"设备软件已是最新版本!"];
            }
        }
    } failure:^(NSError *error) {
        [self showToastText:[error localizedDescription]];
    }];
    
}
     
     
-(void)showNewVersionTip:(WIFIModel *)wifi versionInfo:(NSDictionary *)info
{
    NSString *fileUrl = [info objectForKey:@"file_url"];
    NSString *logMessage = [info objectForKey:@"log_message"];
    NSArray *fileUrlArray = [fileUrl componentsSeparatedByString:@"/"];
    
    if ([fileUrlArray count] > 0) {
        NSMutableString *fileName = [[NSMutableString alloc] initWithString:[fileUrlArray lastObject]];
        NSArray *fileNameArray = [fileName componentsSeparatedByString:@"-"];
        fileName = [[NSMutableString alloc] initWithString:[fileNameArray lastObject]];
        
        NSRange range = [fileName rangeOfString:@".rk"];
        if (range.length > 0) {
            [fileName replaceCharactersInRange:range withString:@" "];
        }
        if (fileName) {
            logMessage = [NSString stringWithFormat:@"发现设备新固件:%@", fileName];
        }
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:logMessage
                                                   delegate:nil
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"升级", nil];
    [alert showWithCompleteHandler:^(NSInteger buttonIndex) {
        
        if (buttonIndex == 1) {
            [self showConfirmVersionUpdate:wifi info:info];
        }
    }];
}


-(void)showConfirmVersionUpdate:(WIFIModel *)wifi info:(NSDictionary *)info
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:@"大约需要2分钟，请稍后再操作"
                                                   delegate:nil
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定升级", nil];
    [alert showWithCompleteHandler:^(NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            if ([wifi.device_id isEqualToString:self.stationModel.device_id])/// 母猫
            {
                [self upgradeMotherCatWithDeviceID:self.stationModel.device_id fileURL:[info objectForKey:@"file_url"]];
            }
            else /// 子猫
            {
                [self upgradeSonCatWithDeviceID:self.stationModel.device_id masterDeviceID:wifi.device_id fileURL:[info objectForKey:@"file_url"]];
            }
        }
    }];
}



- (void)upgradeMotherCatWithDeviceID:(NSString *)deviceID
                             fileURL:(NSString *)fileURL;
{
    [self.wifiHelper upgradeMotherCatWithDeviceID:deviceID fileURL:fileURL success:^(BOOL succ, id responseObject, NSString *msg) {
        if (responseObject)
        {
            NSString *upgrade = responseObject[@"upgrade"];
            if ([[upgrade lowercaseString] isEqualToString:@"success"])
            {
                [self showToastText:@"固件升级成功!"];
            }
            else{
                [self showToastText:@"固件升级失败!"];
            }
        }
    } failure:^(NSError *error) {
        [self showToastText:[error localizedDescription]];
    }];
}


- (void)upgradeSonCatWithDeviceID:(NSString *)deviceID
                           masterDeviceID:(NSString *)masterDeviceID
                                  fileURL:(NSString *)fileURL
{
    [self.wifiHelper upgradeSonCatWithDeviceID:deviceID masterDeviceID:masterDeviceID fileURL:fileURL success:^(BOOL succ, id responseObject, NSString *msg) {
        if (responseObject)
        {
            NSString *upgrade = responseObject[@"upgrade"];
            if ([[upgrade lowercaseString] isEqualToString:@"success"])
            {
                [self showToastText:@"固件升级成功!"];
            }
            else{
                [self showToastText:@"固件升级失败!"];
            }
        }
    } failure:^(NSError *error) {
        [self showToastText:[error localizedDescription]];
    }];
}

@end
